package com.zk.babala.util;


import android.os.Looper;
import android.widget.Toast;

import com.zk.babala.BabalaApp;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.FutureTask;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;


public class RequestUtil {
    private static final String userAgent = "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36";
    private static final String accept = "*/*";
    public static Map<String, String> headers = new HashMap<>();
    private static List<String> ipList;

    public static void setHeader(String name, String value) {
        headers.put(name, value);
    }
    public static Document get(String url) {
        return Jsoup.parse(sendGetRequest(url));
    }


    public static String getStr(String url) {
        return sendGetRequest(url);

    }

    private static String sendGetRequest(String url) {
        String finalUrl = LineUtil.getLineUtil().swapUrl(url);
        FutureTask<String> task = new FutureTask<>(() -> {
            try (HttpResponse response = HttpRequest.get(finalUrl)
                    .cookie(LineUtil.getLineUtil().getLineCookies())
                    .header(Header.USER_AGENT, userAgent)
                    .header(Header.ACCEPT, accept)
                    .headerMap(headers, true)
                    .setConnectionTimeout(Constant.TIME_OUT)
                    .execute()) {
                if (response.getStatus() != 200) {
                    RequestUtil.toast("请求" + finalUrl + "错误,错误码:" + response.getStatus());
                }
                return response.body();
            }
        });
        new Thread(task).start();
        try {
            return task.get();
        } catch (Exception e) {
            RequestUtil.toast("网络连接异常！" + finalUrl + e.getMessage());
        }
        return "";
    }


    public static List<String> getSuggest(String key) {
        List<String> list = new ArrayList<>();
        String suggestUrl = Constant.SUGGEST_URL + key;
        String result = sendGetRequest(suggestUrl);
        if (StrUtil.isAllNotEmpty(result)) {
            JSONObject jsonObject = JSONUtil.parseObj(result);
            JSONArray data = jsonObject.getJSONArray("data");
            if (data != null) {
                data.forEach(dist -> list.add(((JSONObject) dist).getStr("name")));
            }
        }
        return list;

    }


    public static String putData(String url, String body) {
        FutureTask<String> task = new FutureTask<>(() -> {
            try (HttpResponse response = HttpRequest.put(url)
                    .body(body)
                    .header("User-Agent", userAgent)
                    .header("accept", accept)
                    .setConnectionTimeout(Constant.TIME_OUT)
                    .execute()) {
                return response.body();
            }
        }
        );
        new Thread(task).start();
        try {
            return task.get();
        } catch (Exception e) {
            toast("网络连接异常！" + url + e.getMessage());
        }
        return "";
    }


    public static void toast(String msg) {
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(BabalaApp.getContext(), msg, Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();
    }

    /**
     * 从 assets/ip.txt 中读取随机IP
     *
     * @return 随机IP地址，如果读取失败则返回空字符串
     */
    public static String getRandomIP() {
        if (ipList == null) {
            try {
                InputStream inputStream = BabalaApp.getContext().getAssets().open("ip.txt");
                ipList = new ArrayList<>();
                IoUtil.readUtf8Lines(inputStream, ipList);
            } catch (Exception e) {
                toast("读取IP文件异常！" + e.getMessage());
            }
        }
        return ipList.get(RandomUtil.getRandom().nextInt(ipList.size()));
    }


}
